<template>
  <!-- 引入 BasePageTable 组件 -->
  <BasePageTable
    :tableData="tableData"
    :loading="loading"
    :page-num="pageNum"
    :page-size="pageSize"
    :total="total"
    :tableColumnsData="tableColumnsData"
    @handleQuery="handleQuery"
  >
    <!-- 自定义列内容 -->
    <template #mainImage="{ row }">
      <el-image
        style="width: 100px; height: 100px"
        :src="JSON.parse(row.image)[0].url || ''"
        fit="cover"
      ></el-image>
    </template>

    <template #isTop="{ row }">
      <el-switch
        v-model="row.isTop"
        :active-value="1"
        :inactive-value="0"
        :before-change="() => handleSwitchChange(row.isTop, row)"
      ></el-switch>
    </template>
    <template #status="{ row }">
      <el-switch
        v-model="row.status"
        :active-value="2"
        :inactive-value="1"
        :before-change="() => handleSwitchStatusChange(row.status, row)"
      ></el-switch>
    </template>
    <template #statusDesc="{ row }">
      <el-tag :type="ARTICLE_STATUS_MAP[row.status] || 'info'">
        {{ getLabelByValue(ARTICLE_STATUS, row.status) }}
      </el-tag>
    </template>

    <template #discussFlag="{ row }">
      <el-switch
        v-model="row.isDiscuss"
        :active-value="1"
        :inactive-value="0"
        :before-change="() => handleSwitchDiscussFlag(row.isDiscuss, row)"
      ></el-switch>
    </template>

    <template #operation="{ row }">
      <el-button link type="primary" icon="View" @click="handlePreview(row)">查看</el-button>
      <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
      <el-button link type="primary" icon="Delete" @click="handleDelete(row)">删除</el-button>
    </template>
  </BasePageTable>
</template>

<script setup name="Online">
import {
  changeDiscuss,
  changeStatus,
  changeTopState,
  deleteArticle,
  updateById,
} from "@/api/article";
import { getArticleList } from "@/api/article";
import { ref, watchEffect, onMounted } from "vue";
import BasePageTable from "@/components/BasePageTable/index.vue"; // 引入 BasePageTable 组件
import { ElMessageBox, ElMessage } from "element-plus";
import { getLabelByValue } from "../../../utils/enums/index.js";
import { ARTICLE_STATUS, ARTICLE_STATUS_MAP } from "@/enums/aritcle/aritcle.js";

const reallyUrl = import.meta.env.VITE_API_IMAGE;
const emit = defineEmits(["editArticle", "update:categoryId", "preview"]);

const props = defineProps({
  categoryId: {
    type: Number,
    default: 0,
  },
  type: {
    default: Number || String,
  },
  /**
   * 查询参数
   */
  queryParams: {
    type: Object,
    default: () => {
      return {};
    },
  },
  tableColumnsData: {
    type: Array,
    default: () => {
      return [
        {
          label: "标题",
          prop: "title",
          align: "center",
          showOverflowTooltip: true,
        },
        {
          label: "主图",
          prop: "mainImage",
          align: "center",
          customSlot: "mainImage", // 自定义插槽名称
        },
        {
          label: "状态",
          align: "center",
          customSlot: "statusDesc", // 自定义插槽名称
        },
        {
          label: "是否隐藏",
          prop: "status",
          align: "center",
          customSlot: "status", // 自定义插槽名称
        },
        {
          label: "是否置顶",
          prop: "isTop",
          align: "center",
          customSlot: "isTop", // 自定义插槽名称
        },
        {
          label: "是否开启评论",
          prop: "discussFlag",
          align: "center",
          customSlot: "discussFlag", // 自定义插槽名称
        },
        {
          label: "操作",
          align: "center",
          fixed: "right",
          customSlot: "operation", // 自定义插槽名称
          width: 250,
        },
      ];
    },
  },
});

const loading = ref(false);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const tableData = ref([]);
// 方案1：使用 watchEffect
watchEffect(() => {
  if (props.categoryId) {
    pageNum.value = 1;
    console.log(pageNum.value);
    getList();
  }
});

/** 查询列表 */
function getList(params = {}) {
  loading.value = true;
  const reallyParams = {
    types: [props.type],
    ...props.queryParams,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...params,
  };
  !!props.categoryId && (reallyParams.categoryId = props.categoryId);
  getArticleList(reallyParams)
    .then((response) => {
      tableData.value = response.list;
      total.value = response.total;
    })
    .catch((err) => {
      console.log(err, "err");
    })
    .finally(() => {
      loading.value = false;
    });
}
/**
 * 外部可以调用，并传入参数对象，会直接合并
 * 初始化列表
 * @param params 查询参数
 */
const initList = (params = {}) => {
  pageNum.value = 1;
  getList(params);
};

/** 搜索按钮操作 */
function handleQuery(val) {
  pageNum.value = val.pageNum;
  pageSize.value = val.pageSize;
  getList();
}

/** 编辑按钮操作 */
function handleEdit(row) {
  emit("editArticle", row);
}

/** 删除按钮操作 */
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`是否确认删除名称为"${row.title}"的文章?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await deleteArticle(row.id);
    ElMessage.success("删除成功");
    getList();
  } catch (err) {
    console.log(err, "err");
  }
};

async function handleSwitchChange(val, row) {
  try {
    await changeTopState({
      id: row.id,
      isTop: val === 1 ? 0 : 1,
    });
    ElMessage.success(`操作成功`);
    getList();
    return true;
  } catch (err) {
    console.log(err, "err");
    return false;
  }
}

async function handleSwitchStatusChange(val, row) {
  try {
    await changeStatus({
      id: row.id,
      status: val === 1 ? 2 : 1,
    });
    ElMessage.success(`操作成功`);
    getList();
    return true;
  } catch (err) {
    console.log(err, "err");
    return false;
  }
}

async function handleSwitchDiscussFlag(val, row) {
  try {
    await changeDiscuss({
      id: row.id,
      isDiscuss: val === 1 ? 0 : 1,
    });
    ElMessage.success(`操作成功`);
    getList();
    return true;
  } catch (err) {
    console.log(err, "err");
    return false;
  }
}

/**
 * 预览功能
 */
const handlePreview = (row) => {
  console.log(row, "row");
  emit("preview", row);
};
// 如果需要在组件内部修改 categoryId
const updateCategoryId = (newValue) => {
  emit("update:categoryId", newValue);
};

defineExpose({
  initList,
});

onMounted(() => {
  if (!!props.defineProps) {
    console.log("================", props.defineProps.type);
  }
});
</script>
